package com.sxj.features.jdk8;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import com.sxj.features.domain.Student;

/**
 * @author Sun Xiaojie
 */
public class Stream {
	
	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("1", "111");
		map.put("2", "222");
		map.forEach((id,value)->System.out.println(id));
		
		List<Student> students = new ArrayList<>();
		
		
		//stream api 接口方法使用
		List<Student> obtainCardWays = students.stream()
				//过滤
				.filter(student -> student.getId()!=null)
				//对象转换
				.map(student->{
					return Student.builder()
							.id(student.getId()).build();
				})
				//排序
				.sorted((a,b)->a.getId().compareTo(b.getId()))
				//按条件筛选
				.filter(distinctByKey(p->p.getName()))
				//转换为List
				.collect(Collectors.toList());
		
		//递归过深导致  栈溢出
		System.out.println(totalSum(100000, 100000));
	}
	
	public static Integer totalSum(Integer a, Integer b) {
		if (a==1) {
			return b;
		} else {
			a--;
			return totalSum(a,b*a);
		}
	}
	
	/**
	 * 去重
	 * @param keyExtractor
	 * @return
	 */
	private static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> map = new ConcurrentHashMap<>();
        return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

}
